//
//  CommentViewController.m
//  CommentPage
//
//  Created by 欧杨 on 2020/11/27.
//

#import "CommentViewController.h"
#import "CommentTableViewCell.h"
#import "CommentListViewModel.h"
#import "CommentCellViewModel.h"
#import <Masonry.h>

static void *isReady = &isReady;

@interface CommentViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property(strong, nonatomic) CommentListViewModel *viewModel;
@property(strong, nonatomic) UITableView *tableView;
@property(strong, nonatomic) UIView *commentBar;
@property(strong, nonatomic) UITextView *commentField;
@property(strong, nonatomic) UIButton *publish;

@end

@implementation CommentViewController

- (instancetype)initWithContentID:(NSString *)contentID andUserID:(NSString *)userID;
{
    self = [super init];
    if (self) {
        self.viewModel = [[CommentListViewModel alloc] initWithContentID:contentID andUserID:userID];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    //KVO
    [self.viewModel addObserver:self forKeyPath:@"isReady" options:NSKeyValueObservingOptionNew context:isReady];
    
    [self.viewModel getLikeListWithComments];
    
    //Notification about keyboard
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)setupSubviews
{
    if (self.viewModel.comments.count == 0) {
        NSLog(@"无评论");
        UILabel *noComment = [[UILabel alloc] init];
        [noComment setText:@"该内容暂时没有评论"];
        [noComment setFont:[UIFont systemFontOfSize:33]];
        [noComment setTextAlignment:NSTextAlignmentCenter];
        [noComment setTextColor:UIColor.lightGrayColor];
        [noComment setBackgroundColor:UIColor.clearColor];
        [self.view addSubview:noComment];
        [noComment mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    else {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.rowHeight = UITableViewAutomaticDimension;
        self.tableView.estimatedRowHeight = 100;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [tapGesture setNumberOfTapsRequired:1];
        [tapGesture setNumberOfTouchesRequired:1];
        //tapGesture.delegate = self;
        [self.tableView addGestureRecognizer:tapGesture];
    }
    
    /*
     *
     * for page refresh
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
    */
    
    /*
     * add comment bar
     */
    self.commentBar = [[UIView alloc] init];
    self.commentBar.layer.cornerRadius = 10.0;
    self.commentBar.backgroundColor = UIColor.whiteColor;
    self.commentBar.layer.borderColor = UIColor.lightGrayColor.CGColor;
    self.commentBar.layer.borderWidth = 1;
    [self.view addSubview:self.commentBar];
    
    _commentField = [[UITextView alloc] init];
    _commentField.delegate = self;
    _commentField.backgroundColor = UIColor.whiteColor;
    _commentField.layer.borderWidth = 1;
    _commentField.layer.cornerRadius = 10.0;
    [_commentField setFont:[_commentField.font fontWithSize:24]];
    _commentField.layer.borderColor = UIColor.blackColor.CGColor;
    [self.commentBar addSubview:_commentField];
    
    _publish = [UIButton buttonWithType:UIButtonTypeSystem];
    _publish.titleLabel.font = [UIFont systemFontOfSize:28];
    [_publish setTitle:@"发送" forState:UIControlStateNormal];
    [_publish addTarget:self
              action:@selector(publishClicked)
    forControlEvents:UIControlEventTouchUpInside];
    [self.commentBar addSubview:_publish];
    
    //Masonry
    [self.commentBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@80);
        make.bottom.left.right.equalTo(self.view);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.commentBar.mas_top);
    }];
    [_commentField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@50);
        make.centerY.equalTo(_commentBar);
        make.left.equalTo(self.commentBar).offset(20);
        make.right.equalTo(self.commentBar).offset(-100);
    }];
    [_publish mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_commentField);
        make.left.equalTo(_commentField.mas_right).offset(20);
    }];
}

#pragma mark -UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"numberOfRowsInSection = %lu", (unsigned long)self.viewModel.comments.count);
    return self.viewModel.comments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath.row = %ld", (long)indexPath.row);
    NSString *reuseIdentifier = [NSString stringWithFormat:@"%@%ld", @"CommentTableViewCell", (long)indexPath.row];
    CommentCellViewModel *cellViewModel = self.viewModel.comments[indexPath.row];
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    //if (cell != nil) [cell removeFromSuperview];
    if (cell == nil) {
        cell = [[CommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    [cell bindViewModel:cellViewModel];
    return cell;
}

#pragma mark -UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark -KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    //when isReady change
    if (context == isReady) {
        if ([[change valueForKey:NSKeyValueChangeNewKey] boolValue]) {
            [self setupSubviews];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
            /*
            if (self.viewModel.comments.count == 0) {
                UILabel *noComment = [[UILabel alloc] initWithFrame:CGRectMake(UIScreen.mainScreen.bounds.origin.x, UIScreen.mainScreen.bounds.origin.y, 200, 100)];
                [noComment setText:@"该内容暂时没有评论"];
                [noComment setFont:[UIFont systemFontOfSize:33]];
                [self.view addSubview:noComment];
            } else {
                [self setupSubviews];
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            */
        }
    }
}

#pragma mark -BUTTON
- (void)publishClicked
{
    [self.viewModel addNewComment:self.commentField.text];
    [self.commentField endEditing:YES];
}

#pragma mark -REFRESH
- (void) handleRefresh:(id)paramSender
{
  //重新获取已更改的数据源
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    //[self.refreshControl endRefreshing];  //结束刷新，即隐藏刷新控件
  //重新加载表
    
}

#pragma mark -KEYBOARD
- (void)keyboardWillShow:(NSNotification*)notification
{
    NSLog(@"will show");
    NSDictionary*info=[notification userInfo];
    CGSize keyboardSize=[[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    //[_commentBar setCenter:CGPointMake(_commentBar.center.x, _commentBar.center.y-keyboardSize.height)];
    //在这里调整UI位置
    [_commentBar mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@80);
        make.left.right.equalTo(self.view);
        make.bottom.mas_equalTo(-keyboardSize.height);
    }];
}
- (void)keyboardDidHide:(NSNotification*)notification
{
    NSLog(@"will hide");
    //NSDictionary*info=[notification userInfo];
    //CGSize keyboardSize=[[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    //[_commentBar setCenter:CGPointMake(_commentBar.center.x, _commentBar.center.y+keyboardSize.height)];
    [_commentBar mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@80);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
}
- (void)handleTap:(UITapGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        // handling code
        [self.commentField resignFirstResponder];
    }
}
@end
